# Maintainer: Martell Malone <martellmalone@gmail.com>

_realname=conemu
_mingw_suff=mingw-w64-cross
pkgname="${_realname}-git"
replaces="${_realname}"
provides=("${_realname}")
conflicts=("${_realname}")
pkgver=r3330.34a88ed
pkgrel=1
pkgdesc="Customizable Windows console emulator with tabs"
arch=('i686' 'x86_64')
url="http://conemu.github.io/"
license=('custom')
makedepends=("git" "${_mingw_suff}-gcc" "${_mingw_suff}-binutils" "${_mingw_suff}-crt")
# CAUTION:
# Don't remove `!strip' option!  Otherwise, 64-bit version of ConEmu will signal
# errors at startup.
options=('!strip' 'staticlibs' '!emptydirs' '!buildflags')
source=("${_realname}"::"git+https://github.com/Maximus5/ConEmu.git"
        "ConEmu.xml")

md5sums=('SKIP'
         'ef65ed189bc75e38aa3f68e8b2b52359')

case "${CARCH}" in
  i686*)
    _primary_host=i686-w64-mingw32
    _secondary_host=x86_64-w64-mingw32
  ;;
  x86_64*)
    _primary_host=x86_64-w64-mingw32
    _secondary_host=i686-w64-mingw32
  ;;
esac

pkgver() {
  cd "${srcdir}/${_realname}"
  printf 'r%s.%s' "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}

prepare() {
  cd "${srcdir}/${_realname}"

}

build() {

  case "${CARCH}" in
    i686*)
      _CC=i686-w64-mingw32
    ;;
    x86_64*)
      _CC=x86_64-w64-mingw32
    ;;
  esac

  cd "${_realname}/src"

  # NOTE:
  # The ugliest build system I've ever seen, yuck!
  # CAUTION:
  # Don't remove `-static*' switches from `USERLIBSFIRST'!  Otherwise, when
  # running `cmd.exe' (Command Prompt) in ConEmu, it cannot find
  # `libstdc++-6.dll' if it is not in the current `PATH' environment variable.

  for _target in ${_primary_host} ${_secondary_host}; do
    msg "Building ${_realname} for ${_target%%-*}"
    [[ -d ${srcdir}/build-${_target} ]] && rm -rf ${srcdir}/build-${_target}
    cp -rf ${srcdir}/${_realname} ${srcdir}/build-${_target}
    cd ${srcdir}/build-${_target}/src
    CROSS_HOST="${_target}-" make -j1 \
      -f makefile_all_gcc WIDE="1" \
      USERCPP="-pipe -O3 -fomit-frame-pointer -fpermissive -std=c++11" \
      USERLIBSFIRST="-static -static-libgcc -static-libstdc++"
  done
}

package() {
  mkdir -p "${pkgdir}/opt/bin"

  local _suffix=''

  for _target in ${_primary_host} ${_secondary_host}; do
    msg "Installing ${_realname} for ${_target%%-*}"
    cd "${srcdir}/build-${_target}/Release"
    if [ "${CARCH}" == "${_target%%-*}" ]; then
      cp -r "ConEmu.exe" "${pkgdir}/opt/bin/ConEmu.exe"
    fi
    if test "${_target%%-*}" == "x86_64"; then
      _suffix="64"
    else
      _suffix=""
    fi
    cp -r "ConEmu/ConEmuC.exe"  "${pkgdir}/opt/bin/ConEmuC${_suffix}.exe"
    cp -r "ConEmu/ConEmuCD.dll" "${pkgdir}/opt/bin/ConEmuCD${_suffix}.dll"
    cp -r "ConEmu/ConEmuHk.dll" "${pkgdir}/opt/bin/ConEmuHk${_suffix}.dll"
  done

  install -Dm644 ${srcdir}/ConEmu.xml "${pkgdir}"/opt/share/conemu/ConEmu.xml
}
